package com.selfdiscipline.ui.screens.statistics

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.domain.model.ChartData
import com.selfdiscipline.domain.repository.HabitRepository
import com.selfdiscipline.domain.repository.TaskRepository
import com.selfdiscipline.domain.repository.TimerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.YearMonth
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.time.temporal.TemporalAdjusters
import java.util.Locale
import javax.inject.Inject
import kotlin.time.Duration
import androidx.compose.ui.graphics.Color

/**
 * 统计数据UI状态
 */
data class StatisticsUiState(
    val totalFocusTime: Duration = Duration.ZERO,
    val totalTasksCompleted: Int = 0,
    val totalHabitsCompleted: Int = 0,
    val focusTimeData: List<ChartData> = emptyList(),
    val taskCompletionData: List<ChartData> = emptyList(),
    val habitCompletionData: List<ChartData> = emptyList(),
    val focusCategoryData: List<ChartData> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class StatisticsViewModel @Inject constructor(
    private val timerRepository: TimerRepository,
    private val taskRepository: TaskRepository,
    private val habitRepository: HabitRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(StatisticsUiState(isLoading = true))
    val uiState: StateFlow<StatisticsUiState> = _uiState.asStateFlow()
    
    init {
        loadStatistics(TimeRange.WEEKLY)
    }
    
    fun loadStatistics(timeRange: TimeRange) {
        _uiState.value = _uiState.value.copy(isLoading = true, error = null)
        viewModelScope.launch {
            try {
                val (startDate, endDate) = getDateRangeFor(timeRange)
                
                // 加载焦点时间数据
                val focusTimeData = loadFocusTimeData(timeRange, startDate, endDate)
                
                // 加载任务完成数据
                val taskCompletionData = loadTaskCompletionData(timeRange, startDate, endDate)
                
                // 加载习惯完成数据
                val habitCompletionData = loadHabitCompletionData(timeRange, startDate, endDate)
                
                // 加载分类数据
                val categoryData = loadCategoryData(startDate, endDate)
                
                // 获取总计数据
                val totalFocusTime = timerRepository.getTotalFocusTimeInRange(startDate, endDate).first()
                val totalTasksCompleted = taskRepository.getCompletedTasksInRange(startDate, endDate).first().size
                val totalHabitsCompleted = habitRepository.getCompletedHabitsInRange(startDate, endDate).first().size
                
                _uiState.value = _uiState.value.copy(
                    totalFocusTime = totalFocusTime,
                    totalTasksCompleted = totalTasksCompleted,
                    totalHabitsCompleted = totalHabitsCompleted,
                    focusTimeData = focusTimeData,
                    taskCompletionData = taskCompletionData,
                    habitCompletionData = habitCompletionData,
                    focusCategoryData = categoryData,
                    isLoading = false
                )
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    error = e.message ?: "加载统计数据时出错"
                )
            }
        }
    }
    
    /**
     * 获取指定时间范围的起止日期
     */
    private fun getDateRangeFor(timeRange: TimeRange): Pair<LocalDateTime, LocalDateTime> {
        val today = LocalDate.now()
        val startDate: LocalDateTime
        val endDate: LocalDateTime = today.atTime(LocalTime.MAX)
        
        when (timeRange) {
            TimeRange.DAILY -> {
                startDate = today.atTime(LocalTime.MIN)
            }
            TimeRange.WEEKLY -> {
                val weekStart = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                startDate = weekStart.atTime(LocalTime.MIN)
            }
            TimeRange.MONTHLY -> {
                val monthStart = today.withDayOfMonth(1)
                startDate = monthStart.atTime(LocalTime.MIN)
            }
        }
        
        return Pair(startDate, endDate)
    }
    
    /**
     * 加载专注时间数据
     */
    private suspend fun loadFocusTimeData(
        timeRange: TimeRange,
        startDate: LocalDateTime,
        endDate: LocalDateTime
    ): List<ChartData> {
        // 简化实现，返回默认数据
        return when (timeRange) {
            TimeRange.DAILY -> {
                (0..5).map { hour ->
                    ChartData(
                        label = "${hour * 4}:00",
                        value = (5 - hour).toFloat() * 15f,
                        color = Color(0xFF3F51B5)
                    )
                }
            }
            TimeRange.WEEKLY -> {
                val weekdays = listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
                weekdays.mapIndexed { index, day ->
                    ChartData(
                        label = day,
                        value = (7 - index).toFloat() * 10f,
                        color = Color(0xFF3F51B5)
                    )
                }
            }
            TimeRange.MONTHLY -> {
                (1..4).map { week ->
                    ChartData(
                        label = "第${week}周",
                        value = week.toFloat() * 120f,
                        color = Color(0xFF3F51B5)
                    )
                }
            }
        }
    }
    
    /**
     * 加载任务完成数据
     */
    private suspend fun loadTaskCompletionData(
        timeRange: TimeRange,
        startDate: LocalDateTime,
        endDate: LocalDateTime
    ): List<ChartData> {
        // 简化实现，返回默认数据
        return when (timeRange) {
            TimeRange.DAILY -> {
                (0..5).map { hour ->
                    ChartData(
                        label = "${hour * 4}:00",
                        value = (hour + 1).toFloat(),
                        color = Color(0xFF009688)
                    )
                }
            }
            TimeRange.WEEKLY -> {
                val weekdays = listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
                weekdays.mapIndexed { index, day ->
                    ChartData(
                        label = day,
                        value = (index + 1).toFloat(),
                        color = Color(0xFF009688)
                    )
                }
            }
            TimeRange.MONTHLY -> {
                (1..4).map { week ->
                    ChartData(
                        label = "第${week}周",
                        value = week.toFloat() * 5f,
                        color = Color(0xFF009688)
                    )
                }
            }
        }
    }
    
    /**
     * 加载习惯完成数据
     */
    private suspend fun loadHabitCompletionData(
        timeRange: TimeRange,
        startDate: LocalDateTime,
        endDate: LocalDateTime
    ): List<ChartData> {
        // 简化实现，返回默认数据
        return listOf(
            ChartData(label = "晨跑", value = 85f, color = Color(0xFFE91E63)),
            ChartData(label = "阅读", value = 72f, color = Color(0xFFE91E63)),
            ChartData(label = "冥想", value = 65f, color = Color(0xFFE91E63)),
            ChartData(label = "写作", value = 58f, color = Color(0xFFE91E63)),
            ChartData(label = "编程学习", value = 45f, color = Color(0xFFE91E63))
        )
    }
    
    /**
     * 加载分类数据
     */
    private suspend fun loadCategoryData(
        startDate: LocalDateTime,
        endDate: LocalDateTime
    ): List<ChartData> {
        // 简化实现，返回默认数据
        return listOf(
            ChartData(label = "工作", value = 45f, color = Color(0xFF3F51B5)),
            ChartData(label = "学习", value = 30f, color = Color(0xFF009688)),
            ChartData(label = "阅读", value = 15f, color = Color(0xFFE91E63)),
            ChartData(label = "其他", value = 10f, color = Color(0xFFFF9800))
        )
    }
    
    /**
     * 格式化专注时间显示
     */
    fun formatFocusTime(duration: Duration): String {
        val hours = duration.inWholeHours
        val minutes = duration.inWholeMinutes % 60
        
        return if (hours > 0) {
            "$hours 小时 $minutes 分钟"
        } else {
            "$minutes 分钟"
        }
    }
} 